/*
 * @文件描述: 自定义 bottom tab
 * @公司: 山东大学信息学院
 * @作者: 李洪文
 * @Date: 2019-12-19 16:17:39
 * @LastEditors  : 李洪文
 * @LastEditTime : 2019-12-19 20:18:00
 */

import React from 'react';
import { View, Text, StyleSheet, TouchableNativeFeedback } from 'react-native';
import { size, colors } from '@/config';

const px = size.px;

const WIDTH = size.DEVICE_WIDTH;
const MIDDLE_TAB = 2;

const TabBar = props => {
  const { renderIcon, getLabelText, activeTintColor, inactiveTintColor, onTabPress, navigation } = props;
  const { routes, index } = navigation.state;

  const renderItem = (route, activeIndex) => {
    const focused = activeIndex === index;
    const color = focused ? activeTintColor : inactiveTintColor;
    const TabScene = {
      focused: focused,
      route: route,
      tintColor: color,
    };

    /* 隐藏第二个tab---注：必须使用提前占位，否则突出来的tab部分无法点击 */
    if (activeIndex === MIDDLE_TAB) {
      return <View key={route.key} style={[styles.tabItem, { backgroundColor: 'transparent' }]}></View>;
    }

    /* 渲染其他tab */
    return (
      <TouchableNativeFeedback key={route.key} style={styles.tabItem} onPress={() => onTabPress({ route })}>
        <View style={styles.tabItem}>
          {renderIcon(TabScene)}
          <Text style={{ ...styles.tabText, color }}>{getLabelText({ route })}</Text>
        </View>
      </TouchableNativeFeedback>
    );
  };

  // 筛选出第二个tab
  const focused = index === MIDDLE_TAB;
  const color = focused ? activeTintColor : inactiveTintColor;
  const TabScene = {
    focused: focused,
    route: routes[MIDDLE_TAB],
    tintColor: color,
  };
  return (
    <View style={{ width: WIDTH }}>
      <View style={styles.tab}>{routes && routes.map((route, index) => renderItem(route, index))}</View>
      {/*覆盖默认的第二个tab，设置中间按钮凸出样式  使用绝对定位---注：不可以用三段式简化，理由同上*/}
      <View
        style={[
          styles.tabItem,
          {
            position: 'absolute',
            bottom: 0,
            left: (WIDTH * 2) / 5,
            height: px(72),
          },
        ]}
      >
        {renderIcon(TabScene)}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  tab: {
    flexDirection: 'row',
    width: WIDTH,
    borderWidth: 1,
    borderColor: colors.borderColor,
  },
  tabItem: {
    height: px(48),
    width: WIDTH / 5,
    alignItems: 'center',
    justifyContent: 'center',
  },
  tabText: {
    marginTop: 5,
    fontSize: 10,
  },
});

export default TabBar;
